package redis

import (
	"context"

	"github.com/go-redis/redis/v8"

	"gitee.com/mkwchecking/k-scaffold/config"

	"gitee.com/mkwchecking/k-scaffold/pkg/rely/ctx"
)

type DefaultRedis = redis.Client

// ProvideDefault default redis client
func ProvideDefault(ctx context.Context, conf config.Redis) (*DefaultRedis, func(), error) {
	client, err := New(ctx, conf)
	if err != nil {
		return nil, nil, err
	}

	cleanup := func() {
		if err := client.Close(); err != nil {
			panic(err)
		}
	}

	return client, cleanup, nil
}

func GetRedis(c context.Context) (*redis.Client, error) {
	val, err := ctx.Get[*redis.Client](c, ctx.RedisKey{})
	return val, err
}

func SetRedis(c context.Context, client *redis.Client) context.Context {
	return ctx.Set(c, ctx.RedisKey{}, client)
}
